package com.zhuliwei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.entity.LoginUser;
import com.zhuliwei.domain.entity.User;
import com.zhuliwei.mapper.MenuMapper;
import com.zhuliwei.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 实现UserDetailsService接口（根据用户名查用户信息）
 *
 * @author 朱力维
 * @time 2022/10/13 12:45
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUserName, username);
        User user = userMapper.selectOne(lqw);
        //判断是否查询到用户 没有抛出异常
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }
        // 查询权限信息封装（如果是后台用户才需要返回权限信息）
        if (user.getType().equals(SystemConstants.TYPE_ADMIN)) {
            List<String> permissions = menuMapper.selectPermsByUserId(user.getId());
            return new LoginUser(user, permissions);
        }
        //返回用户信息
        return new LoginUser(user,null);
    }
}
